package hjj.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义的zuul过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {

    //定义过滤器类型 pre routing post error
    @Override
    public String filterType() {
        return "pre";
    }

    //指定过滤器的执行顺序 返回值越小执行顺序越高
    @Override
    public int filterOrder() {
        return 1;
    }

    //当前过滤器是否生效 true使用 false不使用
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //执行过滤器中的业务逻辑 身份认证，所有的请求都需要携带一个参数：access-token
    @Override
    public Object run() throws ZuulException {
        //获取上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request请求
        HttpServletRequest request = ctx.getRequest();
        //获取request参数
        String token = request.getParameter("access-token");
        //获取token并进行判断
        if(token == null){
            //拦截请求，认证失败
            ctx.setSendZuulResponse(false);//拦截请求
            ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);//返回错误码
        }
        System.out.println("执行了过滤器");
        return null;
    }
}
